package com.hlf.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hlf.eduservice.entity.EduChapter;
import com.hlf.eduservice.entity.EduVideo;
import com.hlf.eduservice.entity.chapter.ChapterVo;
import com.hlf.eduservice.entity.chapter.VideoVo;
import com.hlf.eduservice.mapper.EduChapterMapper;
import com.hlf.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlf.eduservice.service.EduVideoService;
import com.atguigu.servicebase.GlobalExceptionHandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author hlf
 * @since 2022-11-27
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService videoService;
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapperChapter  =  new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> eduChapterList = baseMapper.selectList(wrapperChapter);


        QueryWrapper<EduVideo> wrapperVideo  =  new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> eduVideoList = videoService.list(wrapperVideo);

        List<ChapterVo> finalList = new ArrayList<>();
        for (int i = 0; i < eduChapterList.size(); i++) {
            EduChapter eduChapter = eduChapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            finalList.add(chapterVo);

        // 创建集合，封装章节的小结
        List<VideoVo> videoList = new ArrayList<>();
        for (int m = 0; m < eduVideoList.size(); m++) {
            EduVideo eduVideo = eduVideoList.get(m);
            if(eduVideo.getChapterId().equals(eduChapter.getId())){
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo,videoVo);
                videoList.add(videoVo);
            }
        }
        chapterVo.setChildren(videoList);
        }

        return finalList;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        int count = videoService.count(wrapper);
        if(count>0){
            throw new GuliException(20001,"不能删除");
        }else{
            int i = baseMapper.deleteById(chapterId);
            return i>0;
        }
    }



}
